package com.ims.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ims.pojo.Role;
import com.ims.service.RoleService;
import com.ims.util.Result;
import com.ims.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author yekka1
 * @description: 角色控制层
 * @date 2022/9/9 15:55
 */
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 查询所有角色
     * @return
     */
    @GetMapping("/findAll")
    public Result<List<Role>> findAll() {
        return roleService.findAll();
    }

    /**
     * 查询所有角色（不包括超级管理员）
     * @return
     */
    @GetMapping("/findWithOutSuper")
    public Result<List<Role>> findWithOutSuper() {
        return roleService.findWithOutSuper();
    }

    @GetMapping("/search")
    public Result<Role> search(@RequestParam(name = "queryString") String queryString) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasText(queryString)) {
            wrapper.like(Role::getRoleName, queryString);
        }
        List<Role> roleList = roleService.list(wrapper);
        return new Result<>(true, StatusCode.OK, "搜索成功", roleList);
    }

    @GetMapping("/findById")
    public Result<Role> findById(@RequestParam(name = "roleId") Integer roleId) {
        Role role = roleService.getById(roleId);
        return new Result<>(true, StatusCode.OK, "查询成功", role);
    }

    @PostMapping("/update")
    public Result update(@RequestBody Role role) {
        LambdaQueryWrapper<Role> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Role::getRoleId, role.getRoleId());
        boolean updateSuccess = roleService.update(role, wrapper);
        if (updateSuccess) {
            return new Result(true, StatusCode.OK, "更新成功");
        } else {
            return new Result(true, StatusCode.ERROR, "更新失败");
        }
    }

}
